package pl.koziolekweb.szkola.JXSimpleWatki;

// JX-SimpleWatki/Watki.java
 
public class Watki {

    volatile int counter;

    public static void main(String[] args) {
        new Watki();
    }

    Watki() {
        Runnable[] runs =
            {
                new Fibo(40L,this), new Fibo(39L,this),
                new Fibo(41L,this), new Fibo(38L,this),
                new Fibo(37L,this), new Fibo(42L,this),
            };
        counter = runs.length;

        for (Runnable r : runs)
            new Thread(r).start();

        System.out.println("Wychodzimy z \"main\"");
    }

    synchronized void finished(long arg, long res) {
        counter = counter - 1;
        System.out.println("Fib(" + arg + ") = " + res +
            ". Zostalo do wykonania " + counter);
    }
}

class Fibo implements Runnable {

    long  arg;
    Watki parent;

    static long fibon(long n) {
        return (n < 2) ? n : fibon(n-2) + fibon(n-1);
    }

    Fibo(long n, Watki w) { arg = n; parent = w; }

    public void run() {
        System.out.println("Fibo(" + arg + ") starting");
        long res = fibon(arg);
        parent.finished(arg,res);
    }
}
